/**
 * 
 */
package com.moyq5.mvcmaker.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.moyq5.mvcmaker.MvcMaker;
import com.moyq5.mvcmaker.WebModule;
import com.moyq5.mvcmaker.freemarker.FreeMarkerFactory;

import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;


/**
 * Json注解代理类生成器
 * @author Moyq5
 * @date 2016年9月27日
 */
public class JacksonMixinMvcMaker implements MvcMaker {

	private static Logger log = LoggerFactory.getLogger(JacksonMixinMvcMaker.class);
	
	/* 生成的文件名后缀 */
	private static final String SUFFIX = "MixIn.java";
	/* 模板文件名 */
	private static final String FTL = "mixIn.ftl";
	
	private WebModule module;
	public JacksonMixinMvcMaker(WebModule module) {
		this.module = module;
	}

	@Override
	public void execute(String entityName) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
		String fileName = entityName + SUFFIX;
		String filePath = module.getPath() + File.separator + (module.getJacksonMixinPackage().replace(".", File.separator));
		File destFile = new File(filePath, fileName);

		log.debug("{}Json注解代理类：{}.{}", 
				new Object[]{destFile.exists() ? "已存在": "创建", module.getJacksonMixinPackage(), fileName});
		
		if (!destFile.exists()) {
			destFile.getParentFile().mkdirs();
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("entityName", entityName);
			model.put("module", module);
			FileWriter fw = new FileWriter(destFile);
			Template temp = FreeMarkerFactory.getCfg().getTemplate(FTL);
			temp.process(model, fw);
		}
		
	}

}
